<template>
  <div class="avatar-uploader-box">
    <el-upload
      class="avatar-uploader"
      list-type="picture-card"
      :action="uploadImgUrl"
      :before-upload="handleBeforeUpload"
      :show-file-list="true"
      :accept="accept"
      :headers="headers"
      :on-success="handleUploadSuccess"
      :on-error="handleUploadError"
      :on-remove="handleDelete"
      :on-preview="handlePictureCardPreview"
      :file-list="fileList"
      ref="imageUpload"
      :class="{hide: number > 0 || !!imageUrl}"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <!-- 上传提示 -->
    <slot name="tip" v-if="showTip">
      <div class="el-upload__tip" slot="tip">
        请上传
        <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b></template>
        <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join('/') }}</b></template>
        的文件
      </div>
    </slot>
    <el-dialog
      :visible.sync="dialogVisible"
      title="预览"
      width="800"
      append-to-body
    >
      <img
        :src="dialogImageUrl"
        style="display: block; max-width: 100%; margin: 0 auto"
      />
    </el-dialog>
  </div>
</template>
<script>
import { getToken } from '@/utils/auth'
export default {
  name: 'Upload',
  props: {
    accept: { // 限制类型
      type: String,
      default: '.jpg,.jpeg,.png,gif,JPG,JPEG,PNG,GIF'
    },
    value: {
      type: String,
      default: ''
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ['png', 'jpg', 'jpeg']
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    },
    // 上传图片服务器地址
    uploadUrl: {
      type: String,
      default: ''
    },
    options: {
      type: Object,
      default: () => {
        return {
          name: 'fileName',
          url: 'url',
        }
      }
    }
  },
  data() {
    return {
      number: 0,
      dialogImageUrl: '',
      dialogVisible: false,
      imageUrl: '',
      uploadList: [],
      fileList: [],
      baseUrl: process.env.VUE_APP_BASE_API,
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
    }
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize)
    },
    // 上传图片服务器地址
    uploadImgUrl() {
      // 如果没有指定上传图片服务器地址，则使用默认地址
      if (!this.uploadUrl) {
        return this.baseUrl + '/common/upload'
      }
      // 判断是否为完整url，如果不是，则拼接baseUrl
      if (this.uploadUrl.indexOf('http') === -1) {
        return this.baseUrl + this.uploadUrl
      }
    }
  },
  // 监听
  watch: {
    value: {
      handler(newValue, oldValue) {
        // console.log(newValue, '/', oldValue)
        // 分割
        this.imageUrl = newValue
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    // 上传前loading加载
    handleBeforeUpload(file) {
      let isImg = false
      if (this.fileType.length) {
        let fileExtension = ''
        if (file.name.lastIndexOf('.') > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
        }
        isImg = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true
          if (fileExtension && fileExtension.indexOf(type) > -1) return true
          return false
        })
      } else {
        isImg = file.type.indexOf('image') > -1
      }

      if (!isImg) {
        this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join('/')}图片格式文件!`)
        return false
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize
        if (!isLt) {
          this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`)
          return false
        }
      }
      this.$modal.loading('正在上传图片，请稍候...')
      this.number++
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.uploadList = [{name:res[this.options.name], url:res[this.options.url]}]
        this.uploadedSuccessfully(file)
      } else {
        this.number--
        this.$modal.closeLoading()
        this.$modal.msgError(res.msg)
        this.$refs.imageUpload.handleRemove(file)
        this.uploadedSuccessfully()
      }
    },
    // 上传结束处理
    uploadedSuccessfully(file) {
        this.fileList = this.uploadList
        this.uploadList = []
        this.number = 0
        this.$emit('input',this.fileList[0].url)
        this.$emit('change', this.fileList[0],file)
        this.$modal.closeLoading()
    },
    // 删除图片
    handleDelete(file) {
      const findex = this.fileList.map(f => f.name).indexOf(file.name)
      if (findex > -1) {
        console.log('删除图片',this.fileList,file)
        this.fileList.splice(findex, 1)
        this.$emit('input','')
        this.$emit('change', this.fileList,file)
      }
    },
    // 上传失败
    handleUploadError() {
      this.$modal.msgError('上传图片失败，请重试')
      this.$modal.closeLoading()
    },
    // 预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
  }
}
</script>
<style lang="scss" scoped>
.avatar-uploader-box {
  .avatar-uploader .el-upload {
    border: 1px dashed #c0ccda;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    background-color: #fbfdff;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }

  .avatar {
    width: 148px;
    height: 148px;
    display: block;
  }

  .msg {
    font-size: 13px;
    color: #555;
  }
}
// .el-upload--picture-card 控制加号部分
::v-deep.hide .el-upload--picture-card {
  display: none;
}

// 去掉动画效果
::v-deep .el-list-enter-active,
::v-deep .el-list-leave-active {
  transition: all 0s;
}
::v-deep .contatiner{
  border: 1px dashed #c0ccda;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  background-color: #fbfdff;
}

::v-deep.hide .el-upload--picture-card {
  display: none;
}
</style>
